//
//  SystemCameraViewController.swift
//  SwiftChatUI
//
//  Created by xzk on 2019/2/26.
//  Copyright © 2019年 xzk. All rights reserved.
//

import UIKit
import MobileCoreServices

class SystemCameraViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let pickerCon = UIImagePickerController()
        pickerCon.sourceType = .photoLibrary
        pickerCon.allowsEditing = true
        pickerCon.delegate = self
        present(pickerCon, animated: true, completion: nil)
    }
}

extension SystemCameraViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        var image: UIImage? = nil
        
        let mediaType: String = info[.mediaType] as? String ?? ""
        if mediaType == kUTTypeImage as String {
            if picker.allowsEditing {
                image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
            } else {
                image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
            }
        }
        
        if let image = image {
            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
        }
        
        picker.dismiss(animated: true, completion: nil)
    }
}


